package com.faiz.algorithm;

import java.util.HashMap;
import java.util.Map;

//leetcode submit region begin(Prohibit modification and deletion)
public class LRU {

    private final int capacity;
    private Map<Integer, Node> cache;
    private Node head;
    private Node tail;

    public LRU(int capacity) {
        this.capacity = capacity;
        cache = new HashMap<>();
    }

    public int get(int key) {
        if (!cache.containsKey(key)) {
            return -1;
        } else {
            Node node = cache.get(key);
            //node是tail,无需任何处理
            if (node.next == null) {
                return node.value;
            } else {
                //将node调整到tail位置,如果这个node就是head
                if (node == head) {

                    head = node.next;
                    head.pre = null;

                } else {
                    head.next = node.next;
                    node.next.pre = head;

                }
            }
            node.next = null;
            node.pre = null;
            tail.next = node;
            node.pre = tail;
            tail = node;
            return node.value;
        }
    }

    public void put(int key, int value) {
        Node node = new Node(key, value);
        if (cache.size() < capacity) {
            cache.put(key, node);
            //初始话加入第一个节点
            if (cache.size() == 1) {
                head = node;
                tail = node;
            } else {
                tail.next = node;
                node.pre = tail;
                tail = node;
            }
        } else {
            cache.put(key, node);
            cache.remove(head.key);
            //当前只有一个节点
            if (cache.size() == 1) {
                //添加新节点
                head = node;
                tail = node;
            } else {
                tail.next = node;
                node.pre = tail;
                tail = node;
                head = head.next;
                head.pre = null;
            }
        }

    }

    private class Node {
        int key;
        int value;
        Node next;
        Node pre;

        Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    public static void main(String[] args) {
        LRU lRUCache = new LRU(2);
        lRUCache.put(1, 1); // 缓存是 {1=1}
        lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
        lRUCache.get(1);    // 返回 1
        lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
        lRUCache.get(2);    // 返回 -1 (未找到)
        lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
        lRUCache.get(1);    // 返回 -1 (未找到)
        lRUCache.get(3);    // 返回 3
        lRUCache.get(4);    // 返回 4
    }
}
